import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:easy_read_comic/internal/api/sms_api.dart';
import 'package:easy_read_comic/internal/api/user_api.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class RegisterController extends GetxController {
  RegisterController(this.tabController);

  late TabController tabController;

  final formKey = GlobalKey<FormState>();

  bool visibility = false;

  String verifyCodeText = "获取验证码";

  bool isGiveVerifyCode = false;

  //倒计时时间
  int countdown = 60;

  TextEditingController emailTextEditingController = TextEditingController();

  TextEditingController codeTextEditingController = TextEditingController();

  TextEditingController passwordTextEditingController = TextEditingController();

  void changeVisibility() {
    this.visibility = !this.visibility;
    update();
  }

  // register 注册
  void register() {
    if (formKey.currentState == null) {
      BotToast.showSimpleNotification(title: "系统错误");
      return;
    }
    if (formKey.currentState!.validate()) {
      formKey.currentState!.save();
      UserApi()
          .register(
              emailTextEditingController.value.text,
              codeTextEditingController.value.text,
              passwordTextEditingController.value.text)
          .then((response) {
        if (response.data['code'] == 1) {
          BotToast.showSimpleNotification(title: "注册成功");
          tabController.index = 0;
        }
      });
    }
  }

  //getEmailVerifyCode 获取邮件验证码
  void getEmailVerifyCode() {
    if (emailTextEditingController.value.text.isEmpty) {
      BotToast.showSimpleNotification(title: "请输入电子邮件");
      return;
    }
    if (this.isGiveVerifyCode) {
      return null;
    }
    //请求接口获取验证码
    SmsApi()
        .sendSms(emailTextEditingController.text, "register")
        .then((response) {
      if (response.data["code"] == 1) {
        this.isGiveVerifyCode = true;
        this.countdown = 60;
        BotToast.showSimpleNotification(title: "发送成功");
        Timer.periodic(Duration(seconds: 1), (timer) {
          this.countdown--;
          if (this.countdown < 1) {
            this.countdown = 60;
            this.isGiveVerifyCode = false;
            this.verifyCodeText = "获取验证码";
            timer.cancel();
          } else {
            this.verifyCodeText = "${this.countdown}秒后重新获取";
          }
          update();
        });
      }
    });
  }
}
